package interview.lock;
import java.util.concurrent.atomic.AtomicReference;

/**
 *  题目:实现一个自旋锁
 *  自旋锁好处 循环比较获取直到成功为止，没有类似wait的阻塞。
 *
 *
 *   通过CAS操作完成自旋，A线程先进来调用myLock方法自己持有锁5秒钟，B随后进来发现当前有线程持有锁。不是null,所以只能通过自旋等待，
 *   直到A释放锁后B随后抢到。
 * **/
public class SpinLock {

    private AtomicReference atomicReference = new AtomicReference();

    public void myLock(){
        System.out.println(Thread.currentThread().getName()+"\t come in (^__^)");
        Thread thread = Thread.currentThread();

        while (!atomicReference.compareAndSet(null,thread)){

        }
    }

    public void unMyLock(){
        Thread thread = Thread.currentThread();
        atomicReference.compareAndSet(thread,null);
        System.out.println(Thread.currentThread().getName()+"\t invoked myLock");

    }

    public static void main(String[] args) {

        SpinLock spinLock = new SpinLock();

        new Thread(()->{
            try {
                spinLock.myLock();
                Thread.sleep(5000);
                spinLock.unMyLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();
        new Thread(()->{
            try {
                spinLock.myLock();
                Thread.sleep(1000);
                spinLock.unMyLock();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t2").start();

    }




}
